package com.itheima.response.g_download;

import com.itheima.response.utils.DownLoadUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/downloadCNServlet")
public class DownloadCNServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取下载文件名称
        String filename = request.getParameter("filename");
        System.out.println(filename);

        //2. 获取文件在服务器的输入流对象
        InputStream in = getServletContext().getResourceAsStream("/img/" + filename);

        //2.1 根据浏览器版本不同,对下载文件中文名进行相应处理
        //1 获取浏览器版本头
        String agent = request.getHeader("user-Agent");
        //2 对下载文件中文名进行相应处理

        filename =  DownLoadUtils.getFileName(agent,filename);
        System.out.println("编码后: " + filename);
        //2.2 设置响应头: 控制浏览器不要解析了, 以附件下载的方式处理服务器返回的数据
        response.setHeader("content-Disposition","attachment;filename="+filename);

        //3. 获取字节输出流
        ServletOutputStream sos = response.getOutputStream();

        //4. IO流拷贝
        IOUtils.copy(in,sos);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
